package com.director.core;

import com.director.core.json.JsonParser;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: Simone Ricciardi
 * Date: 6-giu-2010
 * Time: 11.44.05
 */
@SuppressWarnings("unchecked")
public class FormTransactionData implements DirectTransactionData {

   private Map<String, Object> formData = new HashMap<String, Object>();

   public void put(String paramName, Object paramValue) {
      Object previousParam = this.formData.get(paramName);
      if(previousParam != null) {
         if(!(previousParam instanceof List)) {
            List multipleValues = new ArrayList();
            multipleValues.add(previousParam);
            this.formData.put(paramName, multipleValues);
         } else {
            ((List) previousParam).add(paramValue);
         }
      }
      this.formData.put(paramName, paramValue);
   }

   public <T> T parseValue(int order, Class<T> type) {
      if(order == 0) {
         if(Map.class.isAssignableFrom(type)) {
            return (T) this.formData;
         }

         JsonParser parser = DirectContext.get().getConfiguration().getParser();
         String fromMapToJson = parser.format(this.formData);
         return parser.parse(fromMapToJson, type);
      }

      throw new DirectException("Cannot access to parameter with order: " + order + " with form data");
   }

   @Override
   public <T> T parseValue(String name, Class<T> type) {
      Object value = this.formData.get(name);
      if(value instanceof String) {
         JsonParser parser = DirectContext.get().getConfiguration().getParser();
         value = parser.parse(((String)value), type);
      }
      return (T) value;
   }
}
